package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@SuppressWarnings("all")
/**
 *@ClassName OrderTask
 *@Description TODO
 *@Author @O_o  GW__
 *@Date 2025/6/1 00:06
 *@Version 1.0
 */

@Slf4j
@Component //实例化类， 放入spring容器中
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 定时任务：处理超时订单
     */
//    @Scheduled(cron = "0/5 * * * * ?")   // 每5s执行一次
    @Scheduled(cron = "0 * * * * ?")   // 每分钟执行一次
    public void processTimeoutOrder() {
        log.info("处理超时订单");
        Integer status = Orders.PENDING_PAYMENT;
        LocalDateTime orderTime = LocalDateTime.now().plusMinutes(-15);
        List<Orders> getTimeoutOrders = orderMapper.getByStatusAndOrdersTimeLT(status, orderTime);
        if (getTimeoutOrders != null && getTimeoutOrders.size() > 0) {
            for (Orders orders : getTimeoutOrders) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("支付超时");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
        log.info("处理超时订单完成");
    }

    /**
     * 定时处理一直处于派送中的订单
     */
//    @Scheduled(cron = "1/5 * * * * ?")   // 每5s执行一次
    @Scheduled(cron = "0 0 1 * * ?")// 每天凌晨1点执行一次
    public void processDeliveryOrder() {
        log.info("定时处理一直处于派送中的订单");
        Integer status = Orders.DELIVERY_IN_PROGRESS;
        LocalDateTime orderTime = LocalDateTime.now().plusMinutes(-60);
        List<Orders> getDeliveryOrders = orderMapper.getByStatusAndOrdersTimeLT(status, orderTime);
        if (getDeliveryOrders != null && getDeliveryOrders.size() > 0) {
            for (Orders orders : getDeliveryOrders) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);

            }
        }
         log.info("定时处理一直处于派送中的订单完成");
    }

}
